#This file is part of The Tweetographer.

#The Tweetographer is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#The Tweetographer is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with The Tweetographer.  If not, see <http://www.gnu.org/licenses/>.

import pycurl, json, StringIO, MySQLdb, sys, time, wx, urllib
from tweetParser import *

tweetObjs = []

STREAM_URL = "http://stream.twitter.com/1/statuses/filter.json?locations=" 

class Client:
 def __init__(self, collection):
   self.friends = []
   self.buffer = ""
   self.userid = None
   self.conn = pycurl.Curl()
   self.collection = collection
   self.p = parser()
   self.counter = 0
   self.clock = Counter()
   self.city = 0

 def connect(self, username, password):
   self.conn.setopt(pycurl.USERPWD, "%s:%s" % (username, password))
   self.conn.setopt(pycurl.URL, STREAM_URL)
   self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
   print "Connected to Twitter API. Receiving Tweets."
   self.conn.perform()
   

 def on_receive(self, data):
    self.check_timer()
    self.buffer += data
    content = ""
    if data.endswith("\r\n") and self.buffer.strip():
        self.counter += 1
        content = json.loads(self.buffer)
        self.buffer = ""
        self.collection.add(content) #collection class shouldn't be needed since everything is run on the fly
        if "text" in content:
            t = tweetObject()
            t.userName = u"{0[user][screen_name]}".format(content)
            t.text = u"{0[text]}".format(content)
            try: #if there are coordinates, get them too
                if u"{0[coordinates]}".format(content) != 'None':
                        coordinates = u"{0[coordinates][coordinates]}".format(content).split(',')
                        t.longitude = float(coordinates[0].replace('[',''))
                        t.latitude = float(coordinates[1].replace(']',''))
                else:
                        URL = "http://maps.googleapis.com/maps/api/geocode/json?address=" + "{0[place][full_name]}".format(content) + "&sensor=false"
                        gResponse = urllib.urlopen(URL)
                        jsonResponse = json.loads(gResponse.read())
                        t.longitude = float("{0[results][0][geometry][location][lng]}".format(jsonResponse))
                        t.latitude = float("{0[results][0][geometry][location][lat]}".format(jsonResponse))                        
            except TypeError:
                    pass        
            self.p.translate(t)

 def check_timer(self):
     if self.clock.get_ticks() >= 180:
        try:
            self.p.upTweet.updateCounter(self.counter)
            self.counter = 0
        except MySQLdb.Error:
            pass
    
def run_offline(collection, textfile):
        fileName = textfile
        f = open(fileName)
        global tweetObjs
        for line in f:
            try:
                content = json.loads(line)
                if "text" in content:
                    t = tweetObject()
                    t.userName = "{0[user][screen_name]}".format(content)
                    t.text = "{0[text]}".format(content)
                    try:
                        if u"{0[coordinates]}".format(content) != 'None':
                                coordinates = u"{0[coordinates][coordinates]}".format(content).split(',')
                                t.longitude = float(coordinates[0].replace('[',''))
                                t.latitude = float(coordinates[1].replace(']',''))
                        else:
                                URL = "http://maps.googleapis.com/maps/api/geocode/json?address=" + "{0[place][full_name]}".format(content) + "&sensor=false"
                                gResponse = urllib.urlopen(URL)
                                jsonResponse = json.loads(gResponse.read())
                                t.longitude = float("{0[results][0][geometry][location][lng]}".format(jsonResponse))
                                print t.longitude
                                t.latitude = float("{0[results][0][geometry][location][lat]}".format(jsonResponse))                                    
                    except TypeError:
                        pass
                    tweetObjs.append(t)
                    #client = Client(collection)
                    #findValuable(client.p,t)
            except ValueError, e:
                pass

def run(city,state):
    col = collection()
    client = Client(col)
    Cities = client.p.upTweet.GetCities()
    try:
        client.city = Cities[city,state]['id']
        global STREAM_URL
        STREAM_URL += str(Cities[city,state]['box'])
    except ValueError:
        print 'City not found'
    print "Connecting to Twitter API..."
    client.connect("Tweetographers","uc2302")    

class collection:
 def __init__(self):
    self.tweets=[]
 def add(self,tweet):
        self.tweets.append(tweet)
 def printTweets(self):
     for tweet in tweets:
         print tweet
         
class Counter:
    def __init__(self):
        self.epoch = time.clock()

    def get_ticks(self):
        delta = time.clock() - self.epoch
        return int(delta)

#---------------- run the program -----------------------  
def main(argv=None):
    app = wx.App(False)  
    frame = TweetFrame(None, -1, ' ')  
    frame.Center(wx.BOTH)  
    frame.Show(False)  
    while 1:
        try:
            run('Cincinnati','OH')
        except Exception as e:
            print 'Error logged\n'
            logfile = open('tweetError.log','a')    
            logfile.write(str(e))
            logfile.write('\n')
            logfile.close()
            
class TweetFrame(wx.Frame):  
    def __init__(self, parent, id, title):  
        wx.Frame.__init__(self, parent, -1, title, size = (1, 1),  
            style=wx.FRAME_NO_TASKBAR|wx.NO_FULL_REPAINT_ON_RESIZE)  

        self.tbicon = TweetTaskBarIcon(self)  
        self.tbicon.Bind(wx.EVT_MENU, self.exitApp, id=wx.ID_EXIT)   
        self.Show(True)  

    def exitApp(self,event):  
        self.tbicon.RemoveIcon()  
        self.tbicon.Destroy()  
        sys.exit()

class TweetTaskBarIcon(wx.TaskBarIcon):  
    def __init__(self, parent):  
        wx.TaskBarIcon.__init__(self)  
        self.parentApp = parent  
        self.tweetIcon = wx.Icon("twitter-icon.png",wx.BITMAP_TYPE_PNG)  
        self.CreateMenu()  
        self.SetIconImage()  

    def CreateMenu(self):  
        self.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.ShowMenu)  
        self.menu=wx.Menu()  
        self.menu.AppendSeparator()  
        self.menu.Append(wx.ID_EXIT, "Close App")  

    def ShowMenu(self,event):  
        self.PopupMenu(self.menu)  

    def SetIconImage(self, mail=False):  
        self.SetIcon(self.tweetIcon, "The Tweetographer")  
        
if __name__ == '__main__':  
        main()
    

